/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Control;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 *
 * @author Augusto Wolf
 */
public class VerificaRede {

    public VerificaRede() {
    }
    private int i1, i2, i3, i4;
    private int f1, f2, f3, f4;
    private ArrayList<String> computadoresLigados = null;
    private ArrayList<String> computadoresDesligados = null;
    private int maxThread = 10;
    private int nThreads = 0;
    private int idThread = 0;
    private int nTentativas = 1;
    private int timeout = 100;
    private String administrador = "administrador";
    private String senha = "cen4513muy";

    public void setIntervalo(String inicio, String fim) {
        String i[] = inicio.split("\\.");
        String f[] = fim.split("\\.");

        i1 = Integer.parseInt(i[0]);
        i2 = Integer.parseInt(i[1]);
        i3 = Integer.parseInt(i[2]);
        i4 = Integer.parseInt(i[3]);

        f1 = Integer.parseInt(f[0]);
        f2 = Integer.parseInt(f[1]);
        f3 = Integer.parseInt(f[2]);
        f4 = Integer.parseInt(f[3]);

    }

    public void verifica() {
        //System.out.println("inicia verificação");
        //System.out.println("\tip inicial: " + i1 + "." + i2 + "." + i3 + "." + i4);
        //System.out.println("\tip final:   " + f1 + "." + f2 + "." + f3 + "." + f4);
        computadoresLigados = new ArrayList<>();
        computadoresDesligados = new ArrayList<>();
        Thread t = new Thread() {

            public void run() {
                for (int i = i1; i <= f1; i++) {
                    for (int ii = i2; ii <= f2; ii++) {
                        for (int iii = i3; iii <= f3; iii++) {
                            for (int iiii = i4; iiii <= f4; iiii++) {
                                String ip = i + "." + ii + "." + iii + "." + iiii;
                                verifica(ip, iii);
                            }
                        }
                    }
                }
            }
        };
        t.start();
    }
    public boolean term;

    public void verifica(final String ip, final int subRede) {
        if (computadoresLigados == null) {
            computadoresLigados = new ArrayList<>();
        }
        if (computadoresDesligados == null) {
            computadoresDesligados = new ArrayList<>();
        }
        while (nThreads >= maxThread) {
            try {
                Thread.sleep(500);
            } catch (Exception ex) {
            }
        }

        nThreads++;
        idThread++;

        Thread t = new Thread() {

            int id = idThread;

            @Override
            public void run() {

                String ss = "";
                for (int i = 0; i < subRede; i++) {
                    ss += ("\t");
                }
                String s = "Iniciando Thread " + id + "\t";
                String st = "";
                System.out.println(s + ss + "Inicio " + ip);

                int n = ping(ip);
                while (term) {
                    try {
                        Thread.sleep(50);
                    } catch (Exception ex) {
                    }
                }
                term = true;
                if (n >= 0) {
                    while (!computadoresLigados.add(ip)) {
                        try {
                            Thread.sleep(50);
                        } catch (Exception ex) {
                        }
                        System.out.println("erro adicionar " + ip);
                    }
                    st = "   tempo medio = " + n;
                } else {
                    while (!computadoresDesligados.add(ip)) {
                        try {
                            Thread.sleep(50);
                        } catch (Exception ex) {
                        }
                        System.out.println("erro adicionar " + ip);
                    }
                    st = "ip = " + ip + "   Desligado";
                }


                s = "Finalizando Thread " + id + "\t";
                System.out.println(s + ss + "Fim " + ip + " " + st);

                nThreads--;
                term = false;
            }
        };
        t.start();
    }
    private int nExeptions = 0;

    public int ping(String ip) {
        int tempo = -1;

        String pingResult = "";

        String pingCmd = "ping -n " + nTentativas + " -w " + timeout + " " + ip;

        try {
            Runtime r = Runtime.getRuntime();
            Process p = r.exec(pingCmd);

            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                //System.out.println(inputLine);
                pingResult += inputLine + "\n";
            }
            in.close();


            if (pingResult.contains("tempo")) {
                String s[] = pingResult.split("ms");
                int max = s.length;
                if (max > nTentativas) {
                    max = nTentativas;
                }
                for (int i = 0; i < max; i++) {
                    //System.out.println(s[i]);
                    s[i] = s[i].substring(s[i].lastIndexOf("tempo") + 6);
                    //System.out.println(s[i]);
                    int ii = Integer.parseInt(s[i]);
                    tempo += ii < 1 ? 1 : ii;
                }
                //System.out.println("\t" + tempo + " " + max);
                tempo = tempo / max;
            }
        }//try
        catch (Exception e) {
            tempo = -1;
            nExeptions++;
            System.out.println("nExeptions = " + nExeptions);
            //System.out.println(pingResult);
            //e.printStackTrace();
        }
        return tempo;
    }

    public String user(String ip) {
        String usuario=null;

        String pingCmd = "tasklist /S "+ip+" /V /U "+administrador+" /P "+senha+" /FO CSV";

        try {
            Runtime r = Runtime.getRuntime();
            Process p = r.exec(pingCmd);

            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                String s[] = inputLine.replace("\"", "").split(";");
                if (s[0].contains("explorer.exe")) {
                    return s[5];
                }
            }
            in.close();
        }//try
        catch (Exception e) {
            System.out.println("nExeptions = " + nExeptions);
        }
        return usuario;
    }

    public ArrayList<String> getComputadoresLigados() {
        return computadoresLigados;
    }

    public ArrayList<String> getComputadoresDesligados() {
        return computadoresDesligados;
    }

    public boolean isVerificando() {
        return nThreads > 0;
    }

    public int getMaxThread() {
        return maxThread;
    }

    public int getnThreads() {
        return nThreads;
    }

    public void setMaxThread(int maxThread) {
        this.maxThread = maxThread;
    }
}
